package com.stsdai.sso.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.stsdai.manager.pojo.User;
import com.stsdai.sso.service.UserService;


@Controller
@RequestMapping("user")
public class UserController {

	@Autowired
	private UserService userService;

	// 请求方法 GET
	// URL http://sso.stsdai.com/user/check/{param}/{type}
	/**
	 * 校验数据是否可用
	 * 
	 * @param param
	 * @param type
	 * @return
	 */
	@RequestMapping(value = "check/{param}/{type}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<String> check(HttpServletRequest request, @PathVariable String param,
			@PathVariable Integer type) {
		try {
			Boolean bool = this.userService.check(param, type);

			// 获取callback
			String callback = request.getParameter("callback");

			// 声明返回的数据
			String result = "";

			// 判断callback是否为非空
			if (StringUtils.isNotBlank(callback)) {
				// 如果为非空，表示使用jsonp调用，需要把返回的数据伪装成js数据
				// 使用callback包裹返回的数据
				result = callback + "(" + bool + ")";
			} else {
				// 如果为空，表示没有使用jsonp调用，就啥都不做
				result = "" + bool;
			}

			// 这里就是查询数据，返回200
			return ResponseEntity.ok(result);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 500
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
	}

	private static final ObjectMapper MAPPER = new ObjectMapper();
	/**
	 * 根据ticket查询用户
	 * 
	 * @param ticket
	 * @return
	 */
	@RequestMapping(value = "{ticket}", method = RequestMethod.GET)
	// @ResponseBody
	public ResponseEntity<String> queryUserByTicket(HttpServletRequest request, @PathVariable("ticket") String ticket) {

		try {
			User user = this.userService.queryUserByTicket(ticket);
			String callback = request.getParameter("callback");
			String result = callback + "(" + MAPPER.writeValueAsString(user) + ")";
			// 200
			if (StringUtils.isNotBlank(result)) {
				return ResponseEntity.ok().body(result);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 500
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);

	}

}
